use salvo::prelude::*;
use std::sync::Arc;
use tracing::{info, error};
use utils::response::*;
use serde::{Deserialize, Serialize};

/// 获取字典项请求
#[derive(Debug, Deserialize)]
pub struct GetDictItemReq {
    /// 字典类型
    pub dict_type: String,
    /// 字典键值（可选）
    pub dict_key: Option<String>,
}

/// 字典项响应
#[derive(Debug, Serialize)]
pub struct DictItemRes {
    /// 字典键值
    pub dict_key: String,
    /// 字典值
    pub dict_value: String,
    /// 字典标签
    pub dict_label: String,
    /// 字典类型
    pub dict_type: String,
    /// 排序号
    pub dict_sort: i32,
    /// 状态（1正常 0停用）
    pub status: String,
}

/// 获取字典数据
/// 
/// 根据字典类型获取字典项列表
#[endpoint(
    operation_id = "infra_dict_getDictData",
    tags("基础设施/字典管理"),
    parameters(
        ("dict_type" = String, Query, description = "字典类型"),
        ("dict_key" = Option<String>, Query, description = "字典键值（可选）")
    ),
    responses(
        (status_code = 200, description = "获取成功", body = ApiResponse<Vec<DictItemRes>>),
        (status_code = 400, description = "请求参数错误"),
        (status_code = 500, description = "服务器内部错误")
    )
)]
pub async fn get_dict_data(req: &mut Request) -> SalvoResult<Vec<DictItemRes>> {
    info!("API: 获取字典数据");

    // 解析查询参数
    let dict_type = req.query::<String>("dict_type")
        .ok_or_else(|| StatusError::bad_request().brief("缺少dict_type参数"))?;
    
    let dict_key = req.query::<String>("dict_key");

    info!("API: 获取字典数据 - dict_type: {}, dict_key: {:?}", dict_type, dict_key);

    // 模拟获取字典数据
    let dict_items = match dict_type.as_str() {
        "user_type" => vec![
            DictItemRes {
                dict_key: "1".to_string(),
                dict_value: "1".to_string(),
                dict_label: "普通用户".to_string(),
                dict_type: dict_type.clone(),
                dict_sort: 1,
                status: "1".to_string(),
            },
            DictItemRes {
                dict_key: "2".to_string(),
                dict_value: "2".to_string(),
                dict_label: "管理员".to_string(),
                dict_type: dict_type.clone(),
                dict_sort: 2,
                status: "1".to_string(),
            },
        ],
        "status" => vec![
            DictItemRes {
                dict_key: "0".to_string(),
                dict_value: "0".to_string(),
                dict_label: "停用".to_string(),
                dict_type: dict_type.clone(),
                dict_sort: 1,
                status: "1".to_string(),
            },
            DictItemRes {
                dict_key: "1".to_string(),
                dict_value: "1".to_string(),
                dict_label: "正常".to_string(),
                dict_type: dict_type.clone(),
                dict_sort: 2,
                status: "1".to_string(),
            },
        ],
        _ => {
            error!("不支持的字典类型: {}", dict_type);
            return Err(StatusError::bad_request().brief("不支持的字典类型"));
        }
    };

    // 如果指定了具体的字典键值，则过滤结果
    let filtered_items = if let Some(key) = dict_key {
        dict_items.into_iter()
            .filter(|item| item.dict_key == key)
            .collect()
    } else {
        dict_items
    };

    info!("成功获取字典数据，返回 {} 项", filtered_items.len());
    
    salvo_success_with_message(
        filtered_items,
        &format!("成功获取字典类型 {} 的数据", dict_type)
    )
}

/// 创建字典项请求
#[derive(Debug, Deserialize)]
pub struct CreateDictItemReq {
    /// 字典键值
    pub dict_key: String,
    /// 字典值
    pub dict_value: String,
    /// 字典标签
    pub dict_label: String,
    /// 字典类型
    pub dict_type: String,
    /// 排序号
    pub dict_sort: i32,
    /// 状态（1正常 0停用）
    pub status: String,
}

/// 创建字典项
#[endpoint(
    operation_id = "infra_dict_createDictItem",
    tags("基础设施/字典管理"),
    request_body = CreateDictItemReq,
    responses(
        (status_code = 200, description = "创建成功"),
        (status_code = 400, description = "请求参数错误"),
        (status_code = 500, description = "服务器内部错误")
    )
)]
pub async fn create_dict_item(req: &mut Request) -> SalvoResult<DictItemRes> {
    info!("API: 创建字典项");

    // 解析请求体
    let body = req.parse_json::<CreateDictItemReq>().await
        .map_err(|e| {
            error!("API: 解析请求体失败: {:?}", e);
            StatusError::bad_request().brief("请求体格式错误")
        })?;

    info!("API: 创建字典项 - type: {}, key: {}", body.dict_type, body.dict_key);

    // 模拟创建字典项
    let dict_item = DictItemRes {
        dict_key: body.dict_key,
        dict_value: body.dict_value,
        dict_label: body.dict_label,
        dict_type: body.dict_type,
        dict_sort: body.dict_sort,
        status: body.status,
    };

    info!("成功创建字典项");
    
    salvo_success_with_message(dict_item, "字典项创建成功")
}

/// 获取字典类型列表
#[endpoint(
    operation_id = "infra_dict_getDictTypes",
    tags("基础设施/字典管理"),
    responses(
        (status_code = 200, description = "获取成功", body = ApiResponse<Vec<String>>),
        (status_code = 500, description = "服务器内部错误")
    )
)]
pub async fn get_dict_types() -> SalvoResult<Vec<String>> {
    info!("API: 获取字典类型列表");

    // 模拟字典类型数据
    let dict_types = vec![
        "user_type".to_string(),
        "status".to_string(),
        "gender".to_string(),
        "education".to_string(),
    ];

    info!("成功获取字典类型列表，共 {} 种类型", dict_types.len());
    
    salvo_success_with_message(dict_types, "获取字典类型列表成功")
} 